<template>
  <a-form ref="form" :model="fakeValue" layout="horizontal" v-bind="$attrs">
    <a-row :style="bodyStyle">
      <slot />
    </a-row>
  </a-form>
</template>
<script>
import { provide, ref, reactive, watch } from 'vue'
import { v4 } from 'uuid'
export default {
  name: 'SForm',
  props: {
    value: {
      required: false,
      type: Object,
      default: undefined
    },
    bodyStyle: {
      required: false
    }
  },
  emits: ['error'],
  setup(props, context) {
    const hookName = 'formRegisterHook_' + v4()
    const form = ref()
    const tabs = {}
    const fakeValue = ref(props.value)
    const validate = (success) => {
      form.value
        .validate()
        .then((data) => {
          success(JSON.parse(JSON.stringify(data)), JSON.parse(JSON.stringify(fakeValue.value)))
        })
        .catch((e) => {
          const name = e.errorFields[0].name[0]
          Object.keys(tabs).forEach((id) => {
            tabs[id].toggleTabToField(e.errorFields[0].name[0])
          })
          context.emit('error', e.errorFields[0].name[0])
          setTimeout(() => {
            form.value.scrollToField(e.errorFields[0].name[0])
          }, 200)
        })
    }
    context.expose({ formRegisterHookName: hookName, validate })
    provide(hookName, {
      register: (id, component) => {
        tabs[id] = component
      },
      unRegister: (id) => {
        delete tabs[id]
      }
    })
    return { form, fakeValue }
  },
  watch: {
    value: {
      handler: function (val, oldVal) {
        this.fakeValue = val
      },
      deep: true
    }
  }
}
</script>
